<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ESP32 WiFi配置</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Segoe UI', 'Microsoft YaHei', sans-serif;
        }

        :root {
            --primary: #3498db;
            --primary-dark: #2980b9;
            --secondary: #2ecc71;
            --secondary-dark: #27ae60;
            --dark: #2c3e50;
            --light: #ecf0f1;
            --gray: #95a5a6;
            --danger: #e74c3c;
            --warning: #f39c12;
            --shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
            --transition: all 0.3s ease;
        }

        body {
            background: linear-gradient(135deg, #1a2980, #26d0ce);
            min-height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 20px;
        }

        .container {
            background: white;
            border-radius: 20px;
            box-shadow: var(--shadow);
            width: 100%;
            max-width: 500px;
            overflow: hidden;
            animation: fadeIn 0.6s ease-out;
        }

        .header {
            background: var(--dark);
            color: white;
            padding: 30px 20px;
            text-align: center;
            position: relative;
        }

        .header h1 {
            font-size: 2.2rem;
            margin-bottom: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 12px;
        }

        .header p {
            color: rgba(255, 255, 255, 0.8);
            font-size: 1.1rem;
        }

        .wifi-icon {
            font-size: 2.8rem;
            color: var(--secondary);
            margin-bottom: 15px;
        }

        .form-container {
            padding: 30px;
        }

        .form-group {
            margin-bottom: 25px;
        }

        label {
            display: block;
            margin-bottom: 10px;
            font-weight: 600;
            color: var(--dark);
            font-size: 1.1rem;
        }

        .select-container {
            position: relative;
            margin-bottom: 5px;
        }

        select {
            width: 100%;
            padding: 15px 20px;
            border: 2px solid #e0e0e0;
            border-radius: 12px;
            background: white;
            font-size: 1rem;
            appearance: none;
            transition: var(--transition);
            cursor: pointer;
        }

        select:focus {
            outline: none;
            border-color: var(--primary);
            box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.2);
        }

        .select-container::after {
            content: "\f078";
            font-family: "Font Awesome 6 Free";
            font-weight: 900;
            position: absolute;
            right: 20px;
            top: 50%;
            transform: translateY(-50%);
            color: var(--gray);
            pointer-events: none;
        }

        .input-container {
            position: relative;
        }

        input[type="password"] {
            width: 100%;
            padding: 15px 20px;
            border: 2px solid #e0e0e0;
            border-radius: 12px;
            font-size: 1rem;
            transition: var(--transition);
        }

        input[type="password"]:focus {
            outline: none;
            border-color: var(--primary);
            box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.2);
        }

        .toggle-password {
            position: absolute;
            right: 15px;
            top: 50%;
            transform: translateY(-50%);
            color: var(--gray);
            cursor: pointer;
            transition: var(--transition);
        }

        .toggle-password:hover {
            color: var(--primary);
        }

        .button-group {
            display: flex;
            gap: 15px;
            margin-top: 30px;
        }

        button {
            flex: 1;
            padding: 16px;
            border: none;
            border-radius: 12px;
            font-size: 1.1rem;
            font-weight: 600;
            cursor: pointer;
            transition: var(--transition);
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
        }

        .refresh-btn {
            background: var(--dark);
            color: white;
        }

        .refresh-btn:hover {
            background: #1a252f;
            transform: translateY(-2px);
        }

        .submit-btn {
            background: var(--primary);
            color: white;
        }

        .submit-btn:hover {
            background: var(--primary-dark);
            transform: translateY(-2px);
        }

        .status {
            margin-top: 25px;
            padding: 15px;
            border-radius: 12px;
            background: #f8f9fa;
            display: flex;
            align-items: center;
            gap: 15px;
            transition: var(--transition);
        }

        .status.scanning {
            background-color: rgba(52, 152, 219, 0.1);
        }

        .status.error {
            background-color: rgba(231, 76, 60, 0.1);
        }

        .status.success {
            background-color: rgba(46, 204, 113, 0.1);
        }

        .status-icon {
            font-size: 1.8rem;
            color: var(--gray);
        }

        .status-text {
            font-size: 0.95rem;
            color: var(--dark);
            flex: 1;
        }

        .status-text strong {
            color: var(--primary);
        }

        .status-text .error {
            color: var(--danger);
        }

        .status-text .success {
            color: var(--secondary-dark);
        }

        .footer {
            text-align: center;
            padding: 20px;
            color: var(--gray);
            font-size: 0.9rem;
            border-top: 1px solid #eee;
            display: flex;
            justify-content: space-between;
        }

        .status-indicator {
            display: flex;
            align-items: center;
            gap: 6px;
        }

        .status-dot {
            width: 10px;
            height: 10px;
            border-radius: 50%;
            background: var(--secondary);
        }

        @keyframes fadeIn {
            from {
                opacity: 0;
                transform: translateY(20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        .signal-icon {
            display: inline-block;
            width: 18px;
            height: 14px;
            position: relative;
            margin-left: 8px;
            vertical-align: middle;
        }

        .signal-bar {
            position: absolute;
            bottom: 0;
            background: #27ae60;
            width: 3px;
            border-radius: 2px 2px 0 0;
            transition: all 0.3s ease;
        }

        .signal-bar:nth-child(1) {
            left: 0;
            height: 30%;
        }

        .signal-bar:nth-child(2) {
            left: 5px;
            height: 50%;
        }

        .signal-bar:nth-child(3) {
            left: 10px;
            height: 70%;
        }

        .signal-bar:nth-child(4) {
            left: 15px;
            height: 90%;
        }

        .signal-weak .signal-bar {
            background: var(--danger);
        }

        .signal-weak .signal-bar:nth-child(1) { height: 30%; }
        .signal-weak .signal-bar:nth-child(2) { height: 30%; }
        .signal-weak .signal-bar:nth-child(3) { height: 30%; }
        .signal-weak .signal-bar:nth-child(4) { height: 30%; }

        .signal-medium .signal-bar {
            background: var(--warning);
        }

        .signal-medium .signal-bar:nth-child(1) { height: 30%; }
        .signal-medium .signal-bar:nth-child(2) { height: 50%; }
        .signal-medium .signal-bar:nth-child(3) { height: 70%; }
        .signal-medium .signal-bar:nth-child(4) { height: 30%; }

        @media (max-width: 480px) {
            .header h1 {
                font-size: 1.8rem;
            }
            .button-group {
                flex-direction: column;
            }
            button {
                width: 100%;
            }
            .footer {
                flex-direction: column;
                gap: 8px;
            }
        }
    </style>
</head>

<body>
    <div class="container">
        <div class="header">
            <div class="wifi-icon">
                <i class="fas fa-wifi"></i>
            </div>
            <h1><i class="fas fa-microchip"></i> ESP32 WiFi配置</h1>
            <p>选择网络并输入密码进行连接</p>
        </div>

        <div class="form-container">
            <form id="wifi-form" action="/save" method="POST">
                <div class="form-group">
                    <label for="ssid">选择WiFi网络:</label>
                    <div class="select-container">
                        <select name="ssid" id="ssid" required>
                            <option value="" disabled selected>-- 正在扫描可用网络 --</option>
                        </select>
                    </div>
                    <div class="status" id="status-area">
                        <i class="fas fa-sync-alt status-icon"></i>
                        <div class="status-text">正在扫描可用网络...</div>
                    </div>
                </div>

                <div class="form-group">
                    <label for="password">WiFi密码:</label>
                    <div class="input-container">
                        <input type="password" id="password" name="password" placeholder="输入密码（如无密码请留空）">
                        <span class="toggle-password" onclick="togglePassword()">
                            <i class="fas fa-eye"></i>
                        </span>
                    </div>
                </div>

                <div class="button-group">
                    <button type="button" class="refresh-btn" onclick="refreshNetworks()">
                        <i class="fas fa-sync-alt"></i> 刷新列表
                    </button>
                    <button type="submit" class="submit-btn">
                        <i class="fas fa-plug"></i> 保存并连接
                    </button>
                </div>
            </form>
        </div>
        <div class="footer">
            <p>ESP32 IoT Device | 模式: AP | IP: 192.168.4.1</p>
            <div class="status-indicator">
                <div class="status-dot"></div>
                <span>已连接</span>
            </div>
        </div>
    </div>

    <script>
        // DOM元素
        const statusArea = document.getElementById('status-area');
        const statusText = document.querySelector('.status-text');
        const statusIcon = document.querySelector('.status-icon');
        const selectElement = document.getElementById('ssid');
        const passwordInput = document.getElementById('password');
        const eyeIcon = document.querySelector('.toggle-password i');

        // 页面加载时自动扫描网络
        document.addEventListener('DOMContentLoaded', function() {
            refreshNetworks();
        });

        // 密码显示切换功能
        function togglePassword() {
            if (passwordInput.type === 'password') {
                passwordInput.type = 'text';
                eyeIcon.classList.replace('fa-eye', 'fa-eye-slash');
            } else {
                passwordInput.type = 'password';
                eyeIcon.classList.replace('fa-eye-slash', 'fa-eye');
            }
        }

        // 刷新网络列表
        function refreshNetworks() {
            // 更新UI状态
            statusArea.classList.remove('error', 'success');
            statusArea.classList.add('scanning');
            statusIcon.style.animation = 'spin 1s linear infinite';
            statusText.innerHTML = '正在扫描可用网络...';
            
            // 调用API获取WiFi列表
            fetch('/wifi-list')
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应不正常');
                    }
                    return response.json();
                })
                .then(data => {
                    if (!Array.isArray(data) || data.length === 0) {
                        throw new Error('未找到可用网络');
                    }
                    updateNetworkList(data);
                })
                .catch(error => {
                    handleNetworkError(error);
                });
        }

        // 更新网络列表
        function updateNetworkList(networks) {
            // 清空现有选项
            selectElement.innerHTML = '';
            
            // 添加默认选项
            const defaultOption = document.createElement('option');
            defaultOption.value = '';
            defaultOption.disabled = true;
            defaultOption.selected = true;
            defaultOption.textContent = '-- 请选择网络 --';
            selectElement.appendChild(defaultOption);
            
            // 添加网络选项
            networks.forEach(network => {
                const option = document.createElement('option');
                option.value = network.ssid;
                
                // 创建信号质量指示器
                const signalQuality = getSignalQuality(network.rssi);
                const signalClass = signalQuality.class;
                const signalText = signalQuality.text;
                
                option.innerHTML = `
                    ${network.ssid} 
                    <span class="signal-icon ${signalClass}">
                        <span class="signal-bar"></span>
                        <span class="signal-bar"></span>
                        <span class="signal-bar"></span>
                        <span class="signal-bar"></span>
                    </span>
                    (${network.rssi}dBm)
                `;
                
                selectElement.appendChild(option);
            });

            // 更新状态信息
            statusArea.classList.remove('scanning');
            statusArea.classList.add('success');
            statusIcon.style.animation = 'none';
            statusIcon.classList.replace('fa-sync-alt', 'fa-check-circle');
            statusIcon.style.color = '#27ae60';
            statusText.innerHTML = `已扫描到 <strong class="success">${networks.length}</strong> 个可用网络，最后刷新: <strong>${formatTime()}</strong>`;
        }

        // 处理网络错误
        function handleNetworkError(error) {
            statusArea.classList.remove('scanning');
            statusArea.classList.add('error');
            statusIcon.style.animation = 'none';
            statusIcon.classList.replace('fa-sync-alt', 'fa-exclamation-triangle');
            statusIcon.style.color = '#e74c3c';
            statusText.innerHTML = `<span class="error">网络扫描失败：${error.message || '未知错误'}</span>`;
            
            // 添加重试选项
            const retryButton = document.createElement('button');
            retryButton.textContent = '重试';
            retryButton.style.marginTop = '10px';
            retryButton.style.padding = '5px 10px';
            retryButton.style.borderRadius = '5px';
            retryButton.style.background = '#e74c3c';
            retryButton.style.color = 'white';
            retryButton.style.border = 'none';
            retryButton.style.cursor = 'pointer';
            retryButton.onclick = refreshNetworks;
            
            statusText.appendChild(document.createElement('br'));
            statusText.appendChild(retryButton);
        }

        // 获取信号质量
        function getSignalQuality(rssi) {
            if (rssi > -50) return { class: '', text: '信号强' };
            if (rssi > -70) return { class: 'signal-medium', text: '信号中' };
            return { class: 'signal-weak', text: '信号弱' };
        }

        // 格式化时间
        function formatTime() {
            const now = new Date();
            return `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}:${now.getSeconds().toString().padStart(2, '0')}`;
        }

        // 表单提交处理
        document.getElementById('wifi-form').addEventListener('submit', function(e) {
            e.preventDefault();
            
            const ssid = selectElement.value;
            const password = passwordInput.value;
            
            if (!ssid) {
                alert('请选择一个WiFi网络');
                return;
            }
            
            // 在实际应用中，这里应提交表单数据到ESP32
            statusArea.classList.add('scanning');
            statusIcon.classList.replace('fa-check-circle', 'fa-sync-alt');
            statusIcon.style.animation = 'spin 1s linear infinite';
            statusText.innerHTML = `正在连接网络: <strong>${ssid}</strong>...`;
            
            // 提交表单数据
            const formData = new FormData();
            formData.append('ssid', ssid);
            formData.append('password', password);
            
            fetch('/save', {
                method: 'POST',
                body: formData
            })
            .then(response => {
                if (response.ok) {
                    return response.text();
                }
                throw new Error('连接失败');
            })
            .then(data => {
                statusArea.classList.remove('scanning');
                statusArea.classList.add('success');
                statusIcon.style.animation = 'none';
                statusIcon.classList.replace('fa-sync-alt', 'fa-check-circle');
                statusIcon.style.color = '#27ae60';
                statusText.innerHTML = `成功连接到网络: <strong class="success">${ssid}</strong>`;
                
                // 显示成功消息
                setTimeout(() => {
                    alert(`成功连接到网络: ${ssid}\n设备将在3秒后重启`);
                }, 500);
            })
            .catch(error => {
                statusArea.classList.remove('scanning');
                statusArea.classList.add('error');
                statusIcon.style.animation = 'none';
                statusIcon.classList.replace('fa-sync-alt', 'fa-exclamation-triangle');
                statusIcon.style.color = '#e74c3c';
                statusText.innerHTML = `<span class="error">连接失败: ${error.message || '未知错误'}</span>`;
            });
        });
    </script>
</body>

</html>